﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections;
using System.Reflection;
using UMC.Wiki.Entities;
using UMC.Web.UI;
using UMC.Web;
using System.IO;

namespace UMC.Wiki.Activities
{



    class SubjectSelfActivity : WebActivity
    {

        void Search(UISection ui, Subject[] subjects, String model, String cmd)
        {
            var subs = new List<Subject>();
            var cateids = new List<ulong>();
            var ids = new List<ulong>();
            var itemIds = new List<ulong>();

            UMC.Data.Utility.Each(subjects, dr =>
            {
                subs.Add(dr);
                if (dr.project_id.HasValue)
                    cateids.Add(dr.project_id ?? 0);
                ids.Add(dr.Id.Value);
                if (dr.project_item_id.HasValue)
                    itemIds.Add(dr.project_item_id.Value);
            });
            var projects = new List<Project>();
            var pitems = new List<ProjectItem>();


            if (itemIds.Count > 0)
            {
                pitems.AddRange(DataFactory.Instance().ProjectItem(itemIds.ToArray()));
            }
            if (cateids.Count > 0)
            {
                projects.AddRange(DataFactory.Instance().Projects(cateids.ToArray()));
            }

            var items = ui;
            var webr = UMC.Web.WebResource.Instance();


            foreach (var sub in subs)
            {
                if (sub.Status == -2)
                {
                    continue;
                }
                // var imgKey = Utility.Guid(sub.Id.Value);

                var click = new Web.UIClick(model, cmd, sub.Id.ToString());
                var data = new UMC.Web.WebMeta().Put("title", sub.Title).Put("reply", (sub.Reply ?? 0).ToString()).Put("look", (sub.Look ?? 0).ToString());


                var cate = projects.Find(g => g.Id == sub.project_id);
                var pitem = pitems.Find(g => g.Id == sub.project_item_id);
                data.Put("pname", cate == null ? "草稿" : cate.Caption);

                data.Put("iname", pitem == null ? "" : pitem.Caption);

                data.Put("time", UMC.Data.Utility.GetDate(sub.LastDate));
                if (cate != null && pitem != null)
                {
                    data.Put("spa", new WebMeta().Put("id", sub.Id).Put("path", String.Format("{0}/{1}/{2}", cate.Code, pitem.Code, sub.Code)));
                }
                else
                {
                    data.Put("sub-id", sub.Id.Value);

                }

                UICMS cell = new UICMS(click, data);
                cell.Formats.Put("left", "{pname}/{iname} {time}");
                cell.Style.Name("licon", new UIStyle().Size(12).Font("wdk")).Name("ricon", new UIStyle().Size(12).Font("wdk"));
                cell.Style.Name("pname").Color(0x777);
                cell.Style.Name("iname").Color(0x777);


                cell.Formats.Put("right", "\uF06E{1:licon} {look}   \uF0E6{1:ricon} {reply}");

                var state = "";
                switch (sub.Status)
                {
                    case 1:
                        break;
                    case 0:
                        state = "未更新";
                        break;
                    case -1:
                        state = "未发布";
                        break;
                }
                if (String.IsNullOrEmpty(state) == false)
                {
                    cell.Tag(state);
                }
                items.Add(cell);
            }
            //ui.Total = total;

        }
        void Me(WebRequest request, WebResponse response)
        {
            var user = this.Context.Token.Identity();


            var form = request.SendValues ?? new UMC.Web.WebMeta();

            var search = new Subject();
            search.user_id = user.Id;


            int limit = UMC.Data.Utility.IntParse(form["limit"] as string, 25);
            int start = UMC.Data.Utility.IntParse(form["start"] as string, 0);

            var category = form["Project"] as string;
            var model = request.Model;


            search.project_id = UMC.Data.Utility.UInt64Parse(category);


            var Keyword = (form["Keyword"] as string ?? String.Empty);
            if (String.IsNullOrEmpty(Keyword) == false)
            {
                search.Title = Keyword;
            }

            var subs = new List<Subject>();
            var cateids = new List<ulong>();
            var itemIds = new List<ulong>();

            //int nextIndex;

            var ui = UISection.Create();
            var u2 = ui;
            int nextIndex;
            var subjects = DataFactory.Instance().Search(search, start, out nextIndex, limit);
            Search(u2, subjects, request.Model, "EditUI");
            if (u2.Length == 0 && start == 0)
            {
                ui.IsNext = false;
                u2.Add("Desc", new UMC.Web.WebMeta().Put("desc", "未有创作的知识").Put("icon", "\uF016"), new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"),
                    new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));
            }
            else
            {
                ui.IsNext = nextIndex > 0;
                ui.StartIndex = nextIndex;
            }
            response.Redirect(ui);
            UMC.Data.Utility.Each(DataFactory.Instance().Search(search, start, out nextIndex, limit), dr =>
            {
                if (dr.Status >= -1)
                {
                    subs.Add(dr);
                    if (dr.project_id.HasValue)
                        cateids.Add(dr.project_id ?? 0);
                    if (dr.project_item_id.HasValue)
                        itemIds.Add(dr.project_item_id.Value);
                }
            });
            var cates = new List<Project>();
            var pitems = new List<ProjectItem>();


            if (itemIds.Count > 0)
            {
                pitems.AddRange(DataFactory.Instance().ProjectItem(itemIds.ToArray()));
            }
            if (cateids.Count > 0)
            {
                cates.AddRange(DataFactory.Instance().Projects(cateids.ToArray()));
            }




            var data = new System.Data.DataTable();
            data.Columns.Add("id");
            data.Columns.Add("title");
            data.Columns.Add("state");
            data.Columns.Add("last");
            data.Columns.Add("owner");
            data.Columns.Add("path");

            foreach (var sub in subs)
            {
                var state = "";
                switch (sub.Status)
                {
                    case 1:
                        break;
                    case 0:
                        state = "未更新";
                        break;
                    case -1:
                        state = "未发布";
                        break;
                }
                var owner = "草稿";
                var cate = cates.Find(g => g.Id == sub.project_id);
                var pitem = pitems.Find(g => g.Id == sub.project_item_id);
                if (cate != null && pitem != null)
                {
                    owner = String.Format("{0}/{1}", cate.Caption, pitem.Caption);
                    data.Rows.Add(sub.Id, sub.Title, state, UMC.Data.Utility.GetDate(sub.LastDate), owner, String.Format("{0}/{1}/{2}", cate.Code, pitem.Code, sub.Code));
                }
                else
                {
                    data.Rows.Add(sub.Id.Value, sub.Title, state, UMC.Data.Utility.GetDate(sub.LastDate), owner);
                }

            };
            var hashc = new System.Collections.Hashtable();
            hashc["data"] = data;
            hashc["next"] = nextIndex > 0;
            if (subs.Count == 0 && start == 0)
            {
                if (String.IsNullOrEmpty(Keyword))
                {
                    hashc["msg"] = "未有创作的知识";
                }
                else
                {
                    hashc["msg"] = String.Format("未有关联“{0}”", Keyword);
                }


            }
            else
            {
                hashc["start"] = nextIndex;
            }
            response.Redirect(hashc);


        }


        public override void ProcessActivity(WebRequest request, WebResponse response)
        {
            var user = this.Context.Token.Identity();
            switch (this.AsyncDialog("Type", "App"))
            {
                case "PC":
                    this.Me(request, response);
                    return;
            }

            var form = request.SendValues ?? new UMC.Web.WebMeta();

            if (form.ContainsKey("limit") == false)
            {
                this.Context.Send(new UISectionBuilder(request.Model, request.Command)

                    .RefreshEvent("Subject.Save", "Subject.Content")
                        .Builder(), true);
            }


            var search = new Subject() { user_id = user.Id };


            int limit = UMC.Data.Utility.IntParse(form["limit"] as string, 25);
            int start = UMC.Data.Utility.IntParse(form["start"] as string, 0);


            var category = form["Project"] as string;


            search.project_id = UMC.Data.Utility.UInt64Parse(category);

            var Keyword = form["Keyword"] ?? string.Empty;


            if (String.IsNullOrEmpty(Keyword) == false)
            {
                search.Title = Keyword;

            }


            var ui = UISection.Create();
            var u2 = ui;

            if (user.IsAuthenticated == false)
            {
                UIDesc desc = new UIDesc(new UMC.Web.WebMeta().Put("desc", "你尚未登录").Put("icon", "\uF016")).Desc("{icon}\n{desc}").Click(
                    new UIClick() { Key = "Login" });

                desc.Style.Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60));
                u2.Add(desc);
                response.Redirect(ui);
            }
            int nextIndex;
            var subjects = DataFactory.Instance().Search(search, start, out nextIndex, limit);
            Search(u2, subjects, request.Model, "EditUI");
            if (u2.Length == 0 && start == 0)
            {
                ui.IsNext = false;
                u2.Add("Desc", new UMC.Web.WebMeta().Put("desc", "未有创作的知识").Put("icon", "\uF016"), new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"),
                    new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));
            }
            else
            {
                ui.IsNext = nextIndex > 0;
                ui.StartIndex = nextIndex;
            }
            response.Redirect(ui);


        }

    }
}